﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.ServiceModel;
using System.ServiceProcess;
using Primer.Contracts.Extensions;

namespace Primer
{
    class Program
    {
        private static ServiceHost _serviceHost;

        static void Main()
        {
            using (Container = GetContainer())
            {
                if (!Environment.UserInteractive)
                {
                    ServiceBase.Run(new[] { new TrackerService() });
                    return;
                }
                // console
                Initialize();
                try
                {
                    OnStart(null);
                    // The service can now be accessed.
                    Console.WriteLine("The service is ready.");
                    Console.WriteLine("Press <ENTER> to terminate service.");
                    Console.ReadLine();
                }
                finally { OnStop(); }
            }
        }

        private static CompositionContainer GetContainer()
        {
            //var addInRoot = Environment.CurrentDirectory + "\\Pipeline";
            var catalog = new DirectoryCatalog(@".\");
            return new CompositionContainer(catalog);
        }

        internal static void Initialize()
        {
            LoadExtensions(Container.GetExportedValues<ISampleExtension>());
        }

        internal static void OnStart(string[] args)
        {
            _serviceHost = new ServiceHost(typeof(Tracker));
            _serviceHost.Open();
            //
            //catch (TimeoutException timeProblem)
            //{
            //    Console.WriteLine(timeProblem.Message);
            //    Console.ReadLine();
            //}
            //catch (CommunicationException commProblem)
            //{
            //    Console.WriteLine(commProblem.Message);
            //    Console.ReadLine();
            //}
        }

        internal static void OnStop()
        {
            if (_serviceHost != null)
                _serviceHost.Close();
        }

        private static void LoadExtensions(IEnumerable<ISampleExtension> extensions)
        {
            foreach (var extension in extensions)
                extension.Foo("");
        }

        public static CompositionContainer Container { get; private set; }
    }
}
